#! /usr/bin/env python """ This file intended to be used within an interactive instruction session It also happens to be an example of bad programming style yet useful for a training session. """ VERBOSE = True #VERBOSE = None class Breakfast1: serving = ["spam & eggs", "toast"] skipping = [] ordered = None if VERBOSE: print """ Beware subtle Python behavior: sharing pre-defined values If you have more than one instance of a class with pre-defined fields, all instances access the same lists. """ alice = Breakfast1() bob = Breakfast1() if VERBOSE: print """ Not only do they have identical content... """ if bob.serving == alice.serving: print "Yes. Both Bob and Alice have identical VALUES." else: print "No. Bob and Alice have different values." if VERBOSE: print """ Both reference the exact SAME object! """ if bob.serving is alice.serving: print "Yes. Both Bob and Alice REFERENCE the SAME data." else: print "No. Bob and Alice REFERENCE DIFFERENT data." if VERBOSE: print """ So then, appending the list of what Bob is skipping with his breakfast order effects Alice's too, even though it might be only Bob who wants spam & eggs without the spam. """ bob.skipping.append("spam") print "Bob skipping:", bob.skipping print "Alice skipping:", alice.skipping if VERBOSE: print """ The above subtlety applies to any pre-assigned value other than None. """ bob.ordered = 1 print "Bob ordered:", bob.ordered print "Alice ordered:", alice.ordered if VERBOSE: print """ As Python permits creating class attributes "on demand" unlike compiled object oriented languages, you can identify unshared fields by assigning a value of None (think: NULL). """ #End.